﻿var BaseUrl = "";
var myWorkflow = {
    FlowDesigner: {},
    IsVersion: false,
    workFlowId: "#myflow",
    TreeId: ".flowtree",
    TreeObj: null,
    Workflow: null,
    workFlowContainerId: ".flow-container",
    flowParamTreeId: ".flowParamTree",
    flowParamFormId: "#flow-params-dynamic-form",
    activtiyContainer: "#activtiy-dynamic-container",//属性容器
    activtiyContainerForm: "#activtiy-dynamic-form",//属性form
    rulesdynamicform: "#flow-rules-dynamic-form",
    ActivtyFunc: null,
    InitMap: {//初始化流程图
        states: {
            '0001': {
                type: 'start', ID: '0001', text: { text: '开始' }, attr: { x: 248, y: 160, width: 50, height: 50 },
                props: { text: { value: '开始' }, temp1: { value: '' }, temp2: { value: '' } }
            }, '0002': {
                type: 'end', ID: '0002', text: { text: '结束' }, attr: { x: 774, y: 170, width: 50, height: 50 },
                props: { text: { value: '结束' }, temp1: { value: '' }, temp2: { value: '' } }
            }, '0003': {
                type: 'normal', ID: '0003', text: { text: '普通' }, attr: { x: 454, y: 121, width: 100, height: 50 },
                props: { text: { value: '普通' }, temp1: { value: '' }, temp2: { value: '' } }
            }
        },
        paths: {
            //path1543929623799: {
            //    lineID: '', lineType: 'path', from: 'rect1', to: 'rect1543929616520', dots: [], text: { text: '', textPos: { x: 0, y: -10 } },
            //    rops: { text: { value: '' }, PathType: { value: '1' } }},
            //path1543929625302: {
            //    lineID: '', lineType: 'path', from: 'rect1543929616520', to: 'rect7', dots: [],
            //    text: { text: '', textPos: { x: 0, y: -10 } }, props: { text: { value: '' }, PathType: { value: '1' } }
        }
    },
    workFlowContainer: null,
    DataFlowDesigner: [],
    InitTree: function () {
        myWorkflow.TreeObj = $(myWorkflow.TreeId).jstree({
            "core": {
                "check_callback": true,//默认为flase，会导致无法使用修改树结构。
                data: function (obj, callback) {
                    var _self = this;
                    var isType = 0;
                    if (obj.original && obj.original.IsType) {
                        isType = obj.original.IsType;
                    }
                    var id = obj.id;
                    Ajax({
                        url: BaseUrl + "/flow/GetTree",
                        data: { parentid: obj.parent == "#" ? "" : obj.id, IsType: isType },
                        success: function (result) {
                            callback.call(_self, result);
                        }
                    });

                }

            },
            "contextmenu": {
                select_node: true,
                show_at_node: true,
                show_Itemed: function (treeNode, items) {

                    var node = treeNode.original;
                    items.create._disabled = true;
                    items.edit._disabled = true;
                    items.delete._disabled = true;
                    items.checkIn._disabled = true;
                    items.checkOut._disabled = true;
                    items.uncheckOut._disabled = true;
                    items.createflow._disabled = true;

                    if (node.IsType == 0 || node.IsType == 1) {
                        items.create._disabled = false;
                    }
                    if (node.IsType == 1) {
                        items.createflow._disabled = false;
                        items.edit._disabled = false;
                        items.delete._disabled = false;
                    }
                    if (node.IsType == 2) {
                        if (node.IsEdited) {

                            items.delete._disabled = false;
                            items.checkIn._disabled = false;
                            items.uncheckOut._disabled = false;
                        }
                        if (!node.IsCheckOut) {
                            items.checkOut._disabled = false;
                        }




                    }
                    //else {
                    //    if (node.IsEdited) {
                    //        items.edit.label = "修改";
                    //        items.edit._disabled = false;
                    //        items.delete._disabled = false;
                    //        items.checkIn._disabled = false;
                    //        items.uncheckOut._disabled = false;
                    //    }
                    //    else if (!node.IsCheckOut) {
                    //        items.edit.label = "查看";
                    //        items.edit._disabled = false;
                    //        items.checkOut._disabled = false;
                    //    }

                    //}
                    return items;
                },
                "items": {
                    "create": {
                        "label": "添加类别",
                        "icon": "fa fa-plus",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            myWorkflow.FlowTypeRemote(inst, treeNode, true);

                        },
                    },
                    "createflow": {
                        "label": "添加工作流",
                        "icon": "fa fa-plus",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var nodeOriginal = inst.get_node(treeNode.reference).original;
                            var node = inst.get_node(treeNode.reference);
                            myWorkflow.FlowRemote(node.id, true, function (result) {
                                var newresult = {
                                    FlowTypeId: result.FlowId,
                                    FlowTypeName: result.FlowName,
                                    icon: "fa fa-user",
                                    ParentId: result.FlowTypeId,
                                    IsType: 2,
                                    text: result.FlowName,
                                    id: result.FlowId,
                                    parent: result.FlowTypeId,
                                    IsCheckOut: true,
                                    IsEdited: true
                                };
                                inst.deselect_all(false);
                                if (node.state.loaded) {
                                    inst.create_node(node.id, newresult);
                                }
                                if (!node.state.opened) {
                                    inst.open_node(treeNode.reference);
                                }
                                inst.select_node(result.id);
                            }, null);

                        },
                    },
                    "edit": {
                        "label": "修改",
                        "icon": "fa fa-paste",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var node1 = inst.get_node(treeNode.reference);
                            var node = node1.original;
                            if (node.IsType == 1) {
                                myWorkflow.FlowTypeRemote(inst, treeNode, false);
                            }
                            else {


                                //myWorkflow.FlowRemote(node.FlowTypeId, false, function (result) {
                                //    node1.original = {
                                //        FlowTypeId: result.FlowId,
                                //        FlowTypeName: result.FlowName,
                                //        icon: "fa fa-check",
                                //        ParentId: result.FlowTypeId,
                                //        IsType: 2,
                                //        text: result.FlowName,
                                //        id: result.FlowId,
                                //        parent: result.FlowTypeId
                                //    };
                                //    node1.icon = "fa fa-user";
                                //    node1.text = result.FlowName;
                                //    inst.edit_node(treeNode.reference, node1);
                                //});
                            }

                        }
                    },

                    "delete": {
                        "label": "删除",
                        "icon": "fa fa-trash",
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);

                            //if ((node.original.IsType < 2 && !node.original.IsCheckOut) || (node.original.IsType>=2&&node.original.IsNewAdd && node.original.IsEdited)) {
                            if (node.original.IsType < 2 || (node.original.IsEdited)) {
                                Notify.Confirm("确定要删除该信息吗？", "删除提示", function () {
                                    Ajax({
                                        url: BaseUrl + "/flow/Delete",
                                        data: { flowid: node.original.FlowTypeId, IsType: node.original.IsType },
                                        success: function (result, message) {
                                            tree.delete_node(treeNode.reference);
                                        }
                                    });
                                });
                            }

                            // }

                        }
                    },


                    "checkOut": {
                        "label": "迁出",
                        "icon": "fa fa-sign-out",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var node = inst.get_node(treeNode.reference);
                            if (!node.original.IsCheckOut) {
                                Notify.Confirm("您确定要调整该流程图吗，迁出后其他用户将无法操作？", "确认提示", function () {
                                    Ajax({
                                        url: BaseUrl + "/flow/CheckOut",
                                        data: { flowid: node.id },
                                        success: function (result, message) {
                                            node.icon = "fa fa-user";
                                            node.original.icon = "fa fa-user";
                                            node.original.IsCheckOut = true;
                                            node.original.IsEdited = true;
                                            inst.edit_node(treeNode.reference, node);
                                            myWorkflow.Ajax(node.original);
                                            // $("#ifrmJobOrgChart").attr("src", "@Url.Content("~/ORG/ORGChart/Index")?id=" + currentNode.data.DepartmentId);
                                        }
                                    });
                                });
                            }
                            else {
                                Notify.Error("该流程图已迁出或者您无权迁出");
                            }
                        }
                    },
                    "checkIn": {
                        "label": "迁入",
                        "icon": "fa fa-sign-in",
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);
                            if (node.original.IsEdited) {
                                Notify.Confirm("您确定要迁入该流程图吗，迁入后将永久覆盖原有结构？", "确认提示", function () {
                                    Ajax({
                                        url: BaseUrl + "/flow/CheckIn",
                                        data: { flowid: node.original.FlowTypeId },
                                        success: function (result, message) {
                                            node.icon = "fa fa-check";
                                            node.original.IsCheckOut = false;
                                            node.original.IsEdited = false;
                                            tree.edit_node(treeNode.reference, node);

                                            myWorkflow.Ajax(node.original);
                                            //$("#ifrmJobOrgChart").attr("src", "@Url.Content("~/ORG/ORGChart/Index")?id=" + currentNode.data.DepartmentId);
                                        }
                                    });
                                });
                            }
                            else {
                                Notify.Error("该部门您无权操作");
                            }
                        }
                    },
                    "uncheckOut": {
                        "label": "撤销迁出",
                        "icon": "fa fa-unlock",
                        "_disabled": true,
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);
                            if (node.original.IsEdited) {
                                Notify.Confirm("您确定要撤销迁出吗，撤销后如果新增流程则会被删除？", "确认提示", function () {
                                    Ajax({
                                        url: BaseUrl + "/flow/Revoke",
                                        data: { flowid: node.original.FlowTypeId },
                                        success: function (result, message) {
                                            node.icon = "fa fa-check";
                                            node.original.IsCheckOut = false;
                                            node.original.IsEdited = false;
                                            tree.edit_node(treeNode.reference, node);
                                            myWorkflow.Ajax(node.original);
                                            //$("#ifrmJobOrgChart").attr("src", "@Url.Content("~/ORG/ORGChart/Index")?id=" + currentNode.data.DepartmentId);
                                        }
                                    });
                                });
                            }
                            else {
                                Notify.Error("该部门您无权操作");
                            }

                        }
                    }

                }
            },

            "plugins": ["wholerow", "contextmenu"]
        }).on('activate_node.jstree', function (obj, e) {
            if (e.node.original.IsOrg) {
                return false;
            }
            if (e.node.original.IsType == 2 || e.node.original.IsType == 3) {
                myWorkflow.Ajax(e.node.original);
            }
            // myWorkflow.Ajax(e.node.id);

        });
    },
    ///流程类别
    FlowTypeRemote: function (tree, treeNode, isAdd) {
        var nodeOriginal = tree.get_node(treeNode.reference).original;
        var node = tree.get_node(treeNode.reference);

        var buttons = [{ id: "close", isClose: true, Name: "关闭" }];

        buttons.push({
            id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                var itemKeys = "";
                FormHelper.ajaxSubmit(modal.find("#flowtype-dynamic-form"), function (result) {

                    //if (nodeOriginal.IsOrg) {
                    //    result.parent = nodeOriginal.OrgId;
                    //}
                    result.icon = "fa fa-gear";
                    if (isAdd) {
                        tree.deselect_all(false);
                        if (node.state.loaded) {
                            tree.create_node(result.parent, result);
                        }
                        if (!node.state.opened) {
                            tree.open_node(treeNode.reference);
                        }
                        tree.select_node(result.id);

                    }
                    else {
                        //node.original = result;
                        //node.icon = "fa fa-user";
                        node.text = result.text;
                        tree.edit_node(treeNode.reference, node);

                    }
                    //  myWorkflow.Init(result.id);
                    modal.modal("hide");
                },null);
                return false;
            }
        });
        var parentid = nodeOriginal.id == "0" ? "" : nodeOriginal.id;
        Notify.Remote({
            Title: "流程类别",
            remote: BaseUrl + "/FlowType/ModalEdit?t=" + Math.random() + (isAdd ? "&ParentId=" + parentid : "&id=" + parentid),
            buttons: buttons,
            loaded: function (modal, id) {
                modal.find("#dynamic-form").CustomForm({
                    isValidate: true,
                    isTable: false
                });


            }
        });
    },
    Ajax: function (node) {
        if (node.IsType < 2) {
            return;
        }
        Ajax({
            url: BaseUrl + "/flow/FlowDesigner?t=" + new Date().toDateString(),
            data: { FlowId: (node.IsType == 2 ? node.FlowTypeId : node.parent), version: node.IsType == 2 ? 0 : node.OrderNum },
            success: function (result) {
                myWorkflow.loadWorkflow(result, false, node.IsType != 2);
            }
        });
    },
    //加载流程基本信息
    FlowRemote: function (id, isAdd, func, flowDesigner) {
        var buttons = [{ id: "close", isClose: true, Name: "关闭" }];

        if ((flowDesigner && flowDesigner.Flow && flowDesigner.Flow.IsEdited) || (!flowDesigner || flowDesigner == null)) {
            buttons.push({
                id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                    var itemKeys = "";
                    if (!modal.find("#flow-dynamic-form").valid()) {
                        return false;
                    }

                    var dataFrm = FormHelper.getFormData(modal.find("#flow-dynamic-form"));
                    Ajax({
                        url: modal.find("#flow-dynamic-form").attr("action"),
                        data: dataFrm,
                        success: function (result) {
                            if (func) {
                                func(result);
                            }
                            else {
                                Notify.alert("保存成功");
                            }
                            modal.modal("hide");
                        }
                    });

                    return false;
                }
            });
        }
        Notify.Remote({
            Title: "流程管理",
            remote: BaseUrl + "/Flow/ModalEdit?t=" + Math.random() + (isAdd ? "&FlowTypeId=" + id : "&id=" + id),
            buttons: buttons,
            loaded: function (modal, id) {
                modal.find("#flow-dynamic-form").CustomForm({
                    isValidate: true,
                    isTable: false
                });


            }
        });
    },
    //初始化流程界面
    InitFlow: function () {
        this.workFlowContainer = $(this.workFlowContainerId);
        $(myWorkflow.flowParamFormId).CustomForm({
            isValidate: true,
            isTable: false,
            Init: true
        });
        $(myWorkflow.activtiyContainerForm).CustomForm({
            isValidate: true,
            isTable: false,
            Init: true
        });
        $(myWorkflow.rulesdynamicform).CustomForm({
            isValidate: true,
            isTable: false,
            Init: true
        });
        $(myWorkflow.activtiyContainerForm).find("input[name!='RecipientName']").on("blur", function () {
            myWorkflow.SaveActivity();
        });
        $(myWorkflow.activtiyContainerForm).find("input[name='RecipientName']").on("click", function ($this) {
            $(this).parent().parent().removeClass("has-error");
            $(this).removeClass("error");
            $(this).parent().parent().find(".field-validation-valid").html("");
            Recipient.Select($this);
        });
        $(myWorkflow.activtiyContainerForm).find(".select2").on("select2:select", function () {
            if ($(this).attr("id") == "RecipientType") {
                $(myWorkflow.activtiyContainerForm).find("#RecipientId").val("");
                $(myWorkflow.activtiyContainerForm).find("#RecipientName").val("");
            }
            myWorkflow.SaveActivity();
        });
        $(myWorkflow.activtiyContainer).find("#ActivityName").on("change", function (e, $this, $text, func) {
            if (myWorkflow.ActivtyFunc && myWorkflow.ActivtyFunc != null) {
                myWorkflow.ActivtyFunc($(myWorkflow.activtiyContainer).find("#ActivityName").val());
                myWorkflow.saveWorkFlow();
            }

        });
    
        $(myWorkflow.activtiyContainerForm).find("#AttrOrderNum,#HttpUrl,#txtRemark").on("change", function (e) {
           
            myWorkflow.SaveActivity();

        });
        $(myWorkflow.activtiyContainer).find("#ActivityName").bind("ActivityChange", function (e, $this, $text, func) {
            if (func) {
                myWorkflow.ActivtyFunc = func;
            }
            //textfunc($(myWorkflow.activtiyContainer).find("#ActivityName").val());
            //myWorkflow.saveWorkFlow();
        });
        $(myWorkflow.activtiyContainer).find(".activtiy-dynamic-container-close").click(function () {
            $(myWorkflow.activtiyContainer).hide();

        });
        $(myWorkflow.activtiyContainer).find(".i-checks").on("ifChanged", function (event) {
            myWorkflow.SaveActivity();
        });
        $(this.flowParamFormId).find("button[type='reset']").click(function () {
            try {

                myWorkflow.FlowParamReset();
            } catch (e) {

            }

            return false;
        });
        $(this.flowParamFormId).submit(function () {
            try {
                if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                    Notify.Error("流程尚未迁出或不是您迁出，无法操作");
                    return false;
                }
                myWorkflow.SaveFlowParam();
            } catch (e) {

            }

            return false;
        });
        $(this.rulesdynamicform).find("button[type='reset']").click(function () {
            try {
                myWorkflow.RuleReset();
            } catch (e) {

            }

            return false;
        });
        $(this.rulesdynamicform).submit(function () {
            try {
                if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                    Notify.Error("流程尚未迁出或不是您迁出，无法操作");
                    return false;
                }
                myWorkflow.SaveRule();
            } catch (e) {

            }

            return false;
        });
        $(".nav-tabs").find(".fa-close").on("click", function () {
            $(this).parent().css({ "display": "none" });

            $(".nav-tabs").find(".flow-map>a").trigger("click");

        });

    },
    ///初始化流程图
    loadWorkflow: function (result, isLog, isVersion) {
        $(this.workFlowId).html("");
        myWorkflow.IsVersion = false;
        myWorkflow.ActivtyFunc = null;
        if (!result || result == null || result == undefined) {
            return;
        }
        if (isLog) {
            result.IsLog = isLog;
            result.Flow.IsEdited = false;
            result.Flow.IsCheckOut = false;
        }
        else {
            $(".nav-tabs").find(".flow-map>a").html(result.Flow.FlowId + "流程图");
        }

        if (isVersion) {
            myWorkflow.IsVersion = true;

            result.Flow.IsEdited = false;
            result.Flow.IsCheckOut = false;
        }

        myWorkflow.FlowDesigner = result;
       
        if (!result.states && result.states == null) {
            result.states = {};
            result.states[result.Flow.FlowId + "001"] = myWorkflow.InitMap.states["0001"];
            result.states[result.Flow.FlowId + "002"] = myWorkflow.InitMap.states["0002"];
            result.states[result.Flow.FlowId + "003"] = myWorkflow.InitMap.states["0003"];
        }

        $("button").removeAttr("disabled");
        if (!result.Flow.IsEdited) {
            $("button[class!='close']").attr("disabled", true);
        }

        if (result.flowParams == null) {
            result.flowParams = {};
        }
        if (result.activities == null) {
            result.activities = {};
        }
        if (result.flowRules == null) {
            result.flowRules = {};
        }
        this.Workflow = $(this.workFlowId).myflow(
            {
                allowStateMutiLine: true,
                basePath: "",
                restore: result,
                width: 800,
                editable: myWorkflow.FlowDesigner.Flow.IsEdited,//把默认修改属性的功能给关闭了
                tools: {
                    contextmenu: function (e, $this, $text, type, func) {
                        if (myWorkflow.FlowDesigner.IsLog) {
                            return false;
                        }

                        var items = [];
                        if (type == "rect") {
                            items.push({
                                text: "节点规则",
                                icon: "fa fa-user",
                                action: "attr",
                                onClick: function (result) {

                                    myWorkflow.loadRule($this.getId());

                                    $(".nav-tabs").children(".flow-rule").css({ "display": "block" });
                                    $(".nav-tabs").find(".flow-rule>a").click();
                                }
                            });

                        }

                        myFlowMenu.renderMenu(e, items);
                    },
                    save: function (data) {

                    },
                    publish: function (data) {
                    },
                    //添加路径时触发 返回true or false
                    addPath: function (paths, from, to, linetype, func) {
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        if (linetype != "path" && (to.getType() == "end" || from.getType() == "start")) {
                            return false;
                        }
                        if (linetype == "path" && to.getType() == "start" || from.getType() == "end") {
                            return false;
                        }
                        var bExists = false;
                        $.each(paths, function (nIndex, nObj) {
                            var fromId = nObj.from().getId();
                            var toId = nObj.to().getId();
                            if (fromId == from.getId() && toId == to.getId()) {
                                console.log(fromId + "+" + toId + "已有同方向连线，无需在设置其他规则连线！");
                                bExists = true;
                                return false;
                            }
                            if (fromId == to.getId() && toId == from.getId() && nObj.getlineType() == linetype) {
                                bExists = true;
                                return false;
                            }

                        });
                        if (bExists)
                            return false;

                        Ajax({
                            url: BaseUrl + "/flow/GetMaxNumber?t=" + new Date().toString(),
                            data: { flowid: myWorkflow.FlowDesigner.Flow.FlowId, isType: 2 },
                            success: function (result) {
                                func(result.max);
                            }
                        });
                        return true;
                    },
                    //添加路径成功时触发
                    addPathed: function (id, data) {
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        myWorkflow.saveWorkFlow();

                    },

                    ///添加节点
                    addRect: function (state, o, func) {
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        if (state.type == "start" || state.type == "end") {
                            return false;
                        }
                        Ajax({
                            url: BaseUrl + "/flow/GetMaxNumber?t=" + new Date().toString(),
                            data: { flowid: myWorkflow.FlowDesigner.Flow.FlowId, isType: 0 },
                            success: function (result) {
                                func(result.max);
                            }
                        });
                        return true;
                    },
                    addRected: function (rect, id, data) {
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        myWorkflow.saveWorkFlow();
                        return true;
                    },
                    clickPath: function (id) {
                        //   console.log("点击线",id)
                    },
                    dblclickPath: function ($this, $text, func) {
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        $("#flow-text-remark-modal").find("#flow-text-remark").val($text.node.textContent);
                        $("#flow-text-remark-modal").find(".modal-title").html($this.getId() + "备注");
                        $("#flow-text-remark-modal").modal("show");
                        $("#flow-text-remark-modal").find(".btn-primary").click(function () {
                            var text = $("#flow-text-remark-modal").find("#flow-text-remark").val();
                            if (!text || text == "") {
                                text = "";
                            }
                            func(text);
                            $("#flow-text-remark-modal").modal("hide");
                            myWorkflow.saveWorkFlow();
                        });
                    },
                    clickRect: function ($this, $text, id, func) {
                        if (myWorkflow.FlowDesigner.IsLog) {
                            return false;
                        }
                        myWorkflow.ActivtiyReset();
                        $(myWorkflow.activtiyContainer).css({ "display": "block" });
                        myWorkflow.setActivtiy($this.getId(), $this);

                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        $(myWorkflow.activtiyContainer).find("#ActivityName").val($text.node.textContent);
                        $(myWorkflow.activtiyContainer).find("#ActivityName").trigger("ActivityChange", [$this, $text, func]);
                        //  alert($(myWorkflow.activtiyContainer).find("#ActivityName").val());

                        // console.log("单击节点，"+data);
                    },
                    dblclickRect: function (id, data) {
                        //console.log("双击节点", id, eval("(" + data + ")"));
                    },
                    //删除线前
                    deletePath: function (id) {
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        // console.log("删除线前", id);
                        return true;
                    },
                    //删除线成功后
                    deletePathed: function (id) {
                        //  console.log("删除线", id);
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        myWorkflow.saveWorkFlow();
                    },
                    deleteRect: function (rect) {

                        // var rect = eval("(" + data + ")");
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        //console.log("删除节点", id, rect);
                        if (rect.getType() == "start" || rect.getType() == "end") {
                            console.log("开始结束节点不能删除");
                            return false;
                        }
                        return true;
                    },
                    deleteRected: function (id, data) {
                        myWorkflow.deleteActivity(id);
                        myWorkflow.saveWorkFlow();
                    },
                    equipmentTypeChange: function (event, value, data) {
                        //console.log(event);
                    },
                    SaveDrag: function () {//拖动后事件
                        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                            return false;
                        }
                        myWorkflow.saveWorkFlow();
                    },
                    revoke: function (id) {

                    }
                }

            });
        $(this.workFlowId).contextmenu(function (e) {
            if (myWorkflow.FlowDesigner.IsLog) {
                return false;
            }
            myFlowMenu.renderMenu(e, [{
                text: "基本信息",
                icon: "fa-info",
                action: "info",
                onClick: function (data) {
                    myWorkflow.FlowRemote(myWorkflow.FlowDesigner.Flow.FlowId, false, function (result) {

                        myWorkflow.FlowDesigner.Flow = result;
                        var node = $(myWorkflow.TreeId).jstree("get_node", result.FlowId);
                        node = $.extend(node, {
                            text: result.FlowName,
                            IsType: 2
                        });

                        node.original = {
                            FlowTypeId: result.FlowId,
                            OrderNum: result.OrderNum,
                            IsType: 2,
                            FlowTypeName: result.FlowName,
                            parent: node.parent
                        };
                        $(myWorkflow.TreeId).jstree().edit_node(null, node);
                        // myWorkflow.saveWorkFlow();
                    }, myWorkflow.FlowDesigner);
                }
            },
            {
                text: "参数",
                icon: " fa-gear",
                action: "param",
                onClick: function (data) {

                    $(".nav-tabs").children(".flow-param").css({ "display": "block" });
                    $(".nav-tabs").find(".flow-param>a").click();
                }
            },
            {
                text: "保存",
                icon: "fa-save",
                action: "Save",
                disabled: myWorkflow.FlowDesigner.Flow.IsEdited,
                onClick: function (data) {
                    if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
                        Notify.Error("流程尚未迁出或不是您迁出，无法操作");
                        return false;
                    }
                    myWorkflow.saveWorkFlow();
                }
            },
            {
                text: "验证流程",
                icon: "fa-check-square-o",
                action: "check",
                disabled: myWorkflow.FlowDesigner.Flow.IsEdited,
                onClick: function (data) {
                    //if (!myWorkflow.FlowDesigner.Flow.IsEdited)
                    //{
                    //    Notify.Error("流程尚未迁出或不是您迁出，无法操作");
                    //    return false;
                    //}
                    Ajax({
                        url: BaseUrl + "/flow/CheckWorkflow",
                        data: { flowid: myWorkflow.FlowDesigner.Flow.FlowId },
                        success: function (result) {
                            Notify.Success("验证成功！");
                        }
                    });
                }
            },
            {
                text: "发布新流程",
                icon: "fa-list",
                action: "publish",
                disabled: myWorkflow.FlowDesigner.Flow.IsEdited,
                onClick: function (data) {

                    if (myWorkflow.IsVersion) {
                        Notify.Error("当前是流程版本信息，无法进行发布！");
                        return false;
                    }

                    var buttons = [{ id: "close", isClose: true, Name: "关闭" }];
                    buttons.push({
                        id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                            var itemKeys = "";
                            var isCover = modal.find("#isCover").parent().hasClass("checked");
                            var version = modal.find("#flow-Version").val();
                            if (parseInt(version) > 0) {
                                if (!isCover) {
                                    Notify.Error("若要覆盖版本，必须确认覆盖！");
                                    return false;
                                }
                            }
                            Notify.Confirm("确定要发布流程吗", "确认发布", function () {
                                Ajax({
                                    url: BaseUrl + "/flow/Publish",
                                    data: { flowid: myWorkflow.FlowDesigner.Flow.FlowId, version: version, isCover: isCover },
                                    success: function (result) {
                                        Notify.Success("发布成功！");
                                        modal.modal("hide");
                                    }
                                });
                            });

                            return false;
                        }
                    });
                    Notify.Remote({
                        Title: "流程版本",
                        remote: BaseUrl + "/Flow/FlowVersion?t=" + Math.random() + "&FlowId=" + myWorkflow.FlowDesigner.Flow.FlowId,
                        modalClass: "col-md-6",
                        buttons: buttons,
                        loaded: function (modal, id) {

                            modal.find("#flow-version-dynamic-form").CustomForm({
                                isValidate: true,
                                isTable: false
                            });
                            modal.find(".modal-content").css({ "margin-left": "200px" });
                            modal.find(".modal-content").addClass("col-md-6");
                            modal.find(".select2").on("select2:open", function () { $(".select2-container--open").css({ "z-index": "9999" }); });

                        }
                    });
                    //Notify.Confirm("确定要发布流程吗", "确认发布", function () {
                    //    Ajax({
                    //        url: BaseUrl + "/flow/Publish",
                    //        data: { flowid: myWorkflow.FlowDesigner.Flow.FlowId },
                    //        success: function (result) {
                    //            Notify.Success("成功！");
                    //        }
                    //    });
                    //});

                    //myWorkflow.saveWorkFlow();
                }
            }
            ]);
            return false;
        });
        myWorkflow.FlowParamReset();
        myWorkflow.loadFlowParams(result);
        myWorkflow.loadRule("");
        myWorkflow.ActivtiyReset();

        myWorkflow.RuleReset();
        // myWorkflow.FlowDesigner = $.extend(myWorkflow.FlowDesigner, result);
        $(myWorkflow.activtiyContainer).css({ "display": "none" });
        $(".nav-tabs").find(".flow-param,.flow-rule").css({ "display": "none" });
        $(".nav-tabs").find(".flow-map>a").trigger("click");
    },
    //保存流程图
    saveWorkFlow: function () {
        var error = $.myflow.checkData();
        //if (error != null) {
        //    Notify.Error(error);
        //    return false;
        //}
        var data = $.myflow.getData();
        data.Flow = myWorkflow.FlowDesigner.Flow;
        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
            return false;
        }
        //data.flowParams = myWorkflow.FlowDesigner.flowParams;
        //data.activities = myWorkflow.FlowDesigner.activities;
        //data.flowRules = myWorkflow.FlowDesigner.flowRules;
        Ajax({
            url: BaseUrl + "/flow/SaveWorkflow",
            data: { Flow: data.Flow, states: data.states, paths: data.paths },
            success: function (result) {

            }
        });
    },
    //加载参数
    loadFlowParams: function (result) {

        if (result.Flow != null) {
            $(this.flowParamFormId).find("input[name='FlowId']").val(result.Flow.FlowId);
            $(this.flowParamFormId).find("input[name='ParamType']").val(0);
            $(this.flowParamFormId).find("input[name='ResourceId']").val(result.Flow.FlowId);
        }
        $(myWorkflow.flowParamTreeId).jstree('destroy').jstree({
            'core': {
                "check_callback": true,
                'data': function (obj, callback) {
                    var newdata = [];
                    if (result.flowParams != null) {
                        $.each(result.flowParams, function (nguid, param) {
                            if (!param.IsDeleted) {
                                newdata.push(param);
                            }
                        });
                    }
                    //, 'selected': true 
                    callback.call(obj, [{
                        "text": result.Flow.FlowName + "参数",
                        "icon": "fa fa-gears",
                        "id": "0",
                        'state': { 'opened': true },
                        "children": newdata
                    }]);
                }
            },
            "contextmenu": {
                select_node: true,
                show_at_node: true,
                show_Itemed: function (treeNode, items) {
                    var node = treeNode.original;
                    items.delete._disabled = true;
                    if (node.id != "0") {
                        items.delete._disabled = false;

                    }
                    //items.create._disabled = true;
                    //
                    return items;
                },
                "items": {
                    "delete": {
                        "label": "删除",
                        "icon": "fa fa-trash",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var node1 = inst.get_node(treeNode.reference);
                            var node = node1.original;

                            //  if (node.original.IsEdited) {
                            Notify.Confirm("您确定删除该参数吗", "确认提示", function () {
                                Ajax({
                                    url: BaseUrl + "/flow/DeleteParams",
                                    data: { flowId: node.FlowId, id: node1.id },
                                    success: function (result, message) {
                                        inst.delete_node(treeNode.reference);
                                        myWorkflow.FlowParamReset();
                                    }
                                });
                            });
                            //}


                        }
                    }

                }
            },

            "plugins": ["wholerow", "contextmenu"]
        }).on('activate_node.jstree', function (obj, e) {


            if (e.node.id != "#" && e.node.id != "0") {

                myWorkflow.setFlowParam(e.node.id);
            }
            //alert(JSON.stringify(e.node));
            //if (e.node.IsOrg) {
            //    return false;
            //}
        });

    },
    //重置页面参数
    FlowParamReset: function () {
        $(this.flowParamFormId).find("button[type='resset']").click();
        $(this.flowParamFormId).find("input").val("");
        if (myWorkflow.FlowDesigner != null && myWorkflow.FlowDesigner.Flow != null) {
            $(this.flowParamFormId).find("input[name='FlowId']").val(myWorkflow.FlowDesigner.Flow.FlowId);
            $(this.flowParamFormId).find("input[name='ParamType']").val(0);
            $(this.flowParamFormId).find("input[name='ResourceId']").val(myWorkflow.FlowDesigner.Flow.FlowId);
        }
    },
    ///设置参数
    setFlowParam: function (id) {
        this.FlowParamReset();
        var flowParam = null;
        if (id != "") {
            flowParam = myWorkflow.FlowDesigner.flowParams[id];
            //console.log(myWorkflow.FlowDesigner.flowParams);
        }
        if (flowParam != null) {
            $.each(flowParam, function (key, value) {
                $(myWorkflow.flowParamFormId).find("[name='" + key + "']").val(value);
            });
        }


    },
    ///保存流程参数
    SaveFlowParam: function () {
        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
            return false;
        }
        if (!$(this.flowParamFormId).valid()) {
            return false;
        }
        var dataFrm = FormHelper.getFormData($(this.flowParamFormId));
        var flowParam = {};
        var exist = false;
        if (myWorkflow.FlowDesigner.flowParams == null) {
            myWorkflow.FlowDesigner.flowParams = {};
        }
        if (dataFrm["id"] != "") {
            flowParam = myWorkflow.FlowDesigner.flowParams[dataFrm["id"]];
            if (flowParam && flowParam != null) {
                exist = true;
            }
        }
        if (!flowParam || flowParam == null) {
            activity = {};
        }
        $.each(dataFrm, function (key, value) {
            flowParam[key] = value;
        });
        Ajax({
            url: $(this.flowParamFormId).attr("action"),
            data: flowParam,
            success: function (result) {
                result.text = result.FlowParamName;
                result.id = result.id;
                result.parent = "0";
                result.icon = "fa fa-gear";
                myWorkflow.FlowDesigner.flowParams[result.id] = result;
                if (!exist) {
                    $(myWorkflow.flowParamTreeId).jstree().create_node("0", result);
                }
                else {
                    var node = $(myWorkflow.flowParamTreeId).jstree("get_node", result.id);
                    node = $.extend(node, result);
                    node.original = result;
                    $(myWorkflow.flowParamTreeId).jstree().edit_node(null, node);
                }
                Notify.Success("保存成功");
                myWorkflow.FlowParamReset();
            }
        });
        return false;
    },
    ///设置节点属性
    setActivtiy: function (id, $this) {
        var activtiy = null;

        if (id != "" && myWorkflow.FlowDesigner.activities != null) {
            activtiy = myWorkflow.FlowDesigner.activities[id];
        }
        var type = $this.getType();
        if (type == "start" || type == "end") {
            $(myWorkflow.activtiyContainerForm).find("input[name='ActivityName']").attr("disabled", true);
        }
        else {
            $(myWorkflow.activtiyContainerForm).find("input[name='ActivityName']").removeAttr("disabled");
        }
        if (!activtiy || activtiy == null) {
            $(myWorkflow.activtiyContainerForm).find("#ActivityId").val(id);

            var value = "";
            switch (type) {
                case "start":
                    value = "1";
                    break;

                case "judge":
                    value = "3";
                    break;
                case "subprocess":
                    value = "4";
                    break;
                case "end":
                    value = "5";
                    break;
                case "queue":
                    value = "6";
                    break;
                default:
                    value = "2";
                    break;
            }
            $(myWorkflow.activtiyContainerForm).find("#ActivityType").val(value);
            $(myWorkflow.activtiyContainerForm).find("#ActivityType").trigger("change");
        }
        if (activtiy == null) {
            $(myWorkflow.activtiyContainerForm).find("input[name='IsNewAdd']").val("true");
        }
        if (activtiy != null) {
            $.each(activtiy, function (key, value) {
                var input = $(myWorkflow.activtiyContainerForm).find("input[name='" + key + "']");
                if (input.attr("type") != "checkbox") {
                    input.val(value);
                }
                else {
                    if (value) {
                        input.parent().addClass("checked");
                    }
                }
                $(myWorkflow.activtiyContainerForm).find("select[name='" + key + "']").each(function () {
                    $(this).val(value);
                    $(this).trigger("change");
                });
            });
        }

    },
    ///重置节点属性
    ActivtiyReset: function () {

        $(this.activtiyContainerForm).find("input").val("");
        $(this.activtiyContainerForm).find("select").val("");
        $(this.activtiyContainerForm).find("select").trigger("change");
        if (myWorkflow.FlowDesigner.Flow.Version == null || myWorkflow.FlowDesigner.Flow.Version == "") {
            myWorkflow.FlowDesigner.Flow.Version = "0";
        }
        $(this.activtiyContainerForm).find("input[name='FlowId']").val(myWorkflow.FlowDesigner.Flow.FlowId);

    },
    ///保存节点属性
    SaveActivity: function () {
    
        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
            return false;
        }
    
        var RecipientNameobj = $(myWorkflow.activtiyContainerForm).find("input[name='RecipientName']");
        RecipientNameobj.parent().parent().removeClass("has-error");
        RecipientNameobj.removeClass("error");
        RecipientNameobj.parent().parent().find(".field-validation-valid").html("");
        if (!$(this.activtiyContainerForm).valid()) {
            return false;
        }
        var RecipientType = $(myWorkflow.activtiyContainerForm).find("select[name='RecipientType']").val();
        if (parseInt(RecipientType) < 30) {

            var RecipientName = RecipientNameobj.val();
            if (!RecipientName || RecipientName == undefined || RecipientName == "") {
                RecipientNameobj.parent().parent().addClass("has-error");
                RecipientNameobj.addClass("error");
                RecipientNameobj.parent().parent().find(".field-validation-valid").html("请输入接收人");
                return false;
            }

        }
      
        var dataFrm = FormHelper.getFormData($(this.activtiyContainerForm));
        var activity = {};
        var exist = false;
        if (myWorkflow.FlowDesigner.activities == null) {
            myWorkflow.FlowDesigner.activities = {};
        }
        if (dataFrm["ActivityId"] && dataFrm["ActivityId"] != "") {
            activity = myWorkflow.FlowDesigner.activities[dataFrm["ActivityId"]];
        }
        if (!activity || activity == null) {
            activity = {};
        }
        $.each(dataFrm, function (key, value) {
            activity[key] = value;
        });
        Ajax({
            url: $(this.activtiyContainerForm).attr("action"),
            data: activity,
            success: function (result) {
                myWorkflow.FlowDesigner.activities[activity["ActivityId"]] = activity;
            }
        });
    },
    deleteActivity: function (id) {
        Ajax({
            url: BaseUrl + "/flow/DeleteActivity",
            data: { flowId: myWorkflow.FlowDesigner.Flow.FlowId, id: id },
            success: function (result, message) {
                myWorkflow.FlowParamReset();
            }
        });
    },
    loadRule: function (id) {
        var rules = myWorkflow.FlowDesigner.flowRules;
        $(this.rulesdynamicform).find("input[name='ActivityId']").val(id);
        $(this.rulesdynamicform).find("input[name='FlowRuleType']").val("0");
        if (rules == null) {
            rules = {};
        }
        if (id && id != "") {
            rules = rules[id];
        }
        this.loadRuleTreeSuccess(rules);
        this.loadRuleTreeReject(rules);
        this.RuleReset();

    },
    ///加载成功规则
    loadRuleTreeSuccess: function (rules) {
        $(".flowRuleTree-success").jstree('destroy').jstree({
            'core': {
                "check_callback": true,
                'data': function (obj, callback) {
                    var newdata = [];
                    if (rules && rules != null) {
                        $.each(rules, function (nguid, param1) {
                            if (!param1.IsDeleted && (param1.FlowRuleType == 0 || param1.FlowRuleType == "0")) {
                                param1 = $.extend(param1, { id: nguid, text: param1.FlowRuleName, icon: "fa fa-gear", parant: "0" });

                                newdata.push(param1);
                            }
                        });
                    }

                    callback.call(obj, {
                        "text": "成功规则",
                        "icon": "fa fa-gears",
                        "id": "0",
                        'state': { 'opened': true },
                        "children": newdata
                    });
                }
            },
            "contextmenu": {
                select_node: true,
                show_at_node: true,
                show_Itemed: function (treeNode, items) {
                    var node = treeNode.original;
                    items.delete._disabled = true;
                    items.create._disabled = true;
                    if (node.id == "0") {
                        items.create._disabled = false;
                    }
                    if (node.id != "0") {
                        items.delete._disabled = false;

                    }
                    return items;
                },
                "items": {
                    "create": {
                        "label": "新增规则",
                        "icon": "fa fa-plus",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            myWorkflow.RuleReset();
                            $(myWorkflow.rulesdynamicform).find("input[name='FlowRuleType']").val("0");

                        }
                    },
                    "delete": {
                        "label": "删除",
                        "icon": "fa fa-trash",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var node1 = inst.get_node(treeNode.reference);
                            var node = node1.original;

                            //  if (node.original.IsEdited) {
                            Notify.Confirm("您确定删除该参数吗", "确认提示", function () {
                                Ajax({
                                    url: BaseUrl + "/flow/DeleteRule",
                                    data: { flowid: node.FlowId, activityid: node.ActivityId, ruleid: node.FlowRuleId },
                                    success: function (result, message) {
                                        inst.delete_node(treeNode.reference);
                                        myWorkflow.RuleReset();
                                    }
                                });
                            });
                            //}


                        }
                    }

                }
            },
            "plugins": ["wholerow", "contextmenu"]
        }).on('activate_node.jstree', function (obj, e) {
            if (e.node.id != "#" && e.node.id != "0") {
                myWorkflow.RuleReset();
                myWorkflow.setRule(e.node.original);
            }

        });

    },
    loadRuleTreeReject: function (rules) {
        $(".flowRuleTree-reject").jstree('destroy').jstree({
            'core': {
                "check_callback": true,
                'data': function (obj, callback) {
                    var newdata = [];
                    if (rules && rules != null) {
                        $.each(rules, function (nguid, param1) {
                            if (!param1.IsDeleted && (param1.FlowRuleType == 1 || param1.FlowRuleType == "1")) {
                                param1 = $.extend(param1, { id: nguid, text: param1.FlowRuleName, icon: "fa fa-gear", parant: "0" });

                                newdata.push(param1);
                            }
                        });
                    }
                    callback.call(obj, {
                        "text": "失败规则",
                        "icon": "fa fa-gears",
                        "id": "0",
                        'state': { 'opened': true },
                        "children": newdata
                    });
                }
            },
            "contextmenu": {
                select_node: true,
                show_at_node: true,
                show_Itemed: function (treeNode, items) {
                    var node = treeNode.original;
                    items.delete._disabled = true;
                    items.create._disabled = true;
                    if (node.id == "0") {
                        items.create._disabled = false;
                    }
                    if (node.id != "0") {
                        items.delete._disabled = false;

                    }
                    return items;
                    return items;
                },
                "items": {
                    "create": {
                        "label": "新增规则",
                        "icon": "fa fa-plus",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            $(myWorkflow.rulesdynamicform).find("input[name='FlowRuleType']").val("1");
                            myWorkflow.RuleReset();

                        }
                    },
                    "delete": {
                        "label": "删除",
                        "icon": "fa fa-trash",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var node1 = inst.get_node(treeNode.reference);
                            var node = node1.original;

                            //  if (node.original.IsEdited) {
                            Notify.Confirm("您确定删除该参数吗", "确认提示", function () {
                                Ajax({
                                    url: BaseUrl + "/flow/DeleteRule",
                                    data: { flowid: node.FlowId, activityid: node.ActivityId, ruleid: node.FlowRuleId },
                                    success: function (result, message) {
                                        inst.delete_node(treeNode.reference);
                                        myWorkflow.RuleReset();
                                    }
                                });
                            });
                            //}


                        }
                    }

                }
            },
            "plugins": ["wholerow", "contextmenu"]
        }).on('activate_node.jstree', function (obj, e) {

            if (e.node.id != "#" && e.node.id != "0") {
                myWorkflow.RuleReset();

                myWorkflow.setRule(e.node.original);
                //$(myWorkflow.activtiyContainerForm).find("#RecipientId").val(e.node.id);
                //$(myWorkflow.activtiyContainerForm).find("#RecipientName").val(e.node.text);
                //myWorkflow.SaveActivity();

            }

        });

    },
    RuleReset: function () {
        var activityid = $(this.rulesdynamicform).find("input[name='ActivityId']").val();
        var FlowRuleType = $(this.rulesdynamicform).find("input[name='FlowRuleType']").val();

        $(this.rulesdynamicform).find("input").val("");
        $(this.rulesdynamicform).find("select").val("");
        $(this.rulesdynamicform).find("input[name='ActivityId']").val(activityid);
        $(this.rulesdynamicform).find("input[name='FlowRuleType']").val(FlowRuleType);
        $(".query-filter").html("");
        var flowParams = myWorkflow.FlowDesigner.flowParams;
        var fields = [];
        if (flowParams != null) {
            $.each(flowParams, function (nguid, param) {
                var type = "string";
                if (!param.IsDeleted) {
                    switch (param.ParamValueType) {
                        case "1":
                            type = "number";
                            break;
                        default:
                            type = "string";
                            break;
                    }
                    fields.push({ name: param.FlowParamName, display: param.FlowParamName, type: type, value: param.DefaultValue });
                }
            });
        }
        var activities = myWorkflow.FlowDesigner.activities;
        if (activities && activities != null) {
            $(this.rulesdynamicform).find("#ToActivity").html("<option value=''>&nbsp;</option>");
            $.each(activities, function (nguid, activity) {
                if (!activity.IsDeleted && nguid != activityid) {
                    if ((FlowRuleType == "1" && activity.ActivityType != "5") || (FlowRuleType == "0" && activity.ActivityType != "1")) {
                        $(myWorkflow.rulesdynamicform).find("#ToActivity").append("<option value='" + activity.ActivityId + "'>" + activity.ActivityName + "</option>");
                    }
                }
            });
        }
        QueryFilter.Init($(".query-filter"), fields);
        $(this.rulesdynamicform).find("textarea").val("");
    },
    setRule: function (node) {
        var rules = myWorkflow.FlowDesigner.flowRules;
        var flowRule = null;

        if (node.FlowRuleId && node.FlowRuleId != "0") {
            if (rules[node.ActivityId] && rules[node.ActivityId] != null) {
                flowRule = rules[node.ActivityId][node.FlowRuleId];
            }
        }

        if (flowRule && flowRule != null) {
            if (flowRule != null) {
                $.each(flowRule, function (key, value) {
                    $(myWorkflow.rulesdynamicform).find("[name='" + key + "']").val(value);
                    $(myWorkflow.rulesdynamicform).find("[name='" + key + "']").trigger("change");
                    //$(myWorkflow.rulesdynamicform).find("select[name='" + key + "']").each(function () {
                    //    $(this).val(value);
                    //    $(this).trigger("change");
                    //});
                });
                QueryFilter.setData(node.group);
            }
        }
    },
    SaveRule: function () {
        if (!myWorkflow.FlowDesigner.Flow.IsEdited) {
            return false;
        }
        if (!$(this.rulesdynamicform).valid()) {
            return false;
        }
        var dataFrm = FormHelper.getFormData($(this.rulesdynamicform));
        if (dataFrm["ToActivity"] == "") {
            Notify.Error("请设置目标节点");
            return false;
        }

        var flowRule = {};
        var exist = false;
        if (myWorkflow.FlowDesigner.flowRules == null) {
            myWorkflow.FlowDesigner.flowRules = {};
        }
        if (dataFrm["FlowRuleId"] && dataFrm["FlowRuleId"] != "") {
            if (myWorkflow.FlowDesigner.flowRules[dataFrm["ActivityId"]] && myWorkflow.FlowDesigner.flowRules[dataFrm["ActivityId"]] != null) {
                flowRule = myWorkflow.FlowDesigner.flowRules[dataFrm["ActivityId"]][dataFrm["FlowRuleId"]];
                exist = true;
            }
        }
        if (!flowRule || flowRule == null) {
            flowRule = {};
        }
        $.each(dataFrm, function (key, value) {
            flowRule[key] = value;
        });
        flowRule.FlowId = myWorkflow.FlowDesigner.Flow.FlowId;
        flowRule.group = QueryFilter.getData();

        if (!flowRule.group || !flowRule.group.rules || flowRule.group.rules.length <= 0) {
            Notify.Error("规则为空，请先设置规则后在保存！");
            return false;
        }
        Ajax({
            url: $(this.rulesdynamicform).attr("action"),
            data: flowRule,
            success: function (result) {
                result.text = result.FlowRuleName;
                result.id = result.FlowRuleId;
                result.parent = "0";
                result.icon = "fa fa-gear";
                if (!myWorkflow.FlowDesigner.flowRules[result.ActivityId] || myWorkflow.FlowDesigner.flowRules[result.ActivityId] == null) {
                    myWorkflow.FlowDesigner.flowRules[result.ActivityId] = {};
                }
                myWorkflow.FlowDesigner.flowRules[result.ActivityId][result.FlowRuleId] = result;
                if (!exist) {

                    if (result.FlowRuleType == 0) {
                        $(".flowRuleTree-success").jstree().create_node("0", result);
                    }
                    else {
                        $(".flowRuleTree-reject").jstree().create_node("0", result);
                    }
                }
                else {
                    if (result.FlowRuleType == 0) {
                        var node = $(".flowRuleTree-success").jstree("get_node", result.id);
                        node = $.extend(node, result);
                        node.original = result;
                        $(".flowRuleTree-success").jstree().edit_node(null, node);
                    }
                    else {
                        var node = $(".flowRuleTree-reject").jstree("get_node", result.id);
                        node = $.extend(node, result);
                        node.original = result;
                        $(".flowRuleTree-reject").jstree().edit_node(null, node);
                    }

                }
                myWorkflow.RuleReset();
            }
        });
    }
};
///选择接受对象
var Recipient =
{
    Select: function ($this) {
        var OrgId = $(myWorkflow.activtiyContainerForm).find("select[name='OrgId']").val();
        var RecipientType = $(myWorkflow.activtiyContainerForm).find("select[name='RecipientType']").val();
        var ActivityType = $(myWorkflow.activtiyContainerForm).find("select[name='ActivityType']").val();
        var ActivityId = $(myWorkflow.activtiyContainerForm).find("input[name='ActivityId']").val();
        if (ActivityType != "4") {
            switch (RecipientType) {
                case "1":
                    this.SelectUser($this, OrgId, RecipientType);
                    break;
                case "2":
                    this.SelectJob($this, OrgId, RecipientType);
                    break;
                case "3":
                    this.SelectDepartment($this, OrgId, RecipientType);
                    break;
                case "4":
                    this.selectGroup($this, OrgId, RecipientType);
                    break;
                case "6":
                case "7":
                case "8":
                    this.selectParams($(this));
                    break;

                case "21":
                case "22":
                case "23":
                    this.selectSteps($(this), ActivityId);
                    break;
            }
        }
        else {
            this.selectProcess($(this), myWorkflow.FlowDesigner.Flow.FlowTypeId);
        }
    },
    SelectUser: function ($this, OrgId, RecipientType) {
        Notify.Remote({
            Title: "用户设置",
            remote: "/org/api/userview?t=" + Math.random(),
            loaded: function (modal, id) {
                modal.find("#allUsertableGrid").CustomForm({
                    isValidate: false,
                    isTable: true,
                    "order": [[1, "desc"]], //默认排序
                    ajaxUrl: "/org/api/GetUsers",
                    "columns": [
                             {
                                 "name": "UserId",
                                 "data": "UserId",
                                 "title": " 用户编号",
                                 "sDefaultContent": "",
                                 "type": 'string',
                                 "format": '',
                                 "bSortable": true
                             }
                            ,
                             {
                                 "name": "UserName",
                                 "data": "UserName",
                                 "title": " 用户名称",
                                 "sDefaultContent": "",
                                 "type": 'string',
                                 "format": '',
                                 "bSortable": true
                             }
                            , {

                                "name": "RealName",
                                "data": "RealName",
                                "title": " 真实姓名",
                                "sDefaultContent": "",
                                "type": 'string',
                                "format": '',
                                "bSortable": true

                            }],
                    "fnServerParams": function (data) {
                        data.keyWord = $("form[datatable='allUsertableGrid']").find("#keyWord").val();
                        data.OrgId = OrgId;
                    }

                });
                $('#allUsertableGrid tbody').on('dblclick', 'tr', function () {
                    var tr = $(this).closest('tr');
                    var id = tr.find('td:first-child').html();//获取id
                    var text = tr.find('td:eq(2)').html();//获取text
                    $(myWorkflow.activtiyContainerForm).find("#RecipientId").val(id);
                    $(myWorkflow.activtiyContainerForm).find("#RecipientName").val(text);
                    myWorkflow.SaveActivity();
                    modal.modal("hide");
                });
            }
        });
    },
    SelectJob: function ($this, OrgId, RecipientType) {
        $(".flow-Tree-JobFunction").jstree('destroy').jstree({
            "core": {
                "check_callback": true,//默认为flase，会导致无法使用修改树结构。
                data: function (obj, callback) {
                    var _self = this;
                    var parentid = obj.id == "#" ? "" : obj.id;
                    var orgid = obj.id == "#" ? OrgId : obj.original.DepartmentId;
                    if (parentid != "" && !obj.original.IsEdited) {
                        orgid = obj.original.DepartmentId;
                    }
                    Ajax({
                        url: "/org/Organizations/GetOrgTree?t=" + new Date().toLocaleTimeString(),
                        data: { id: parentid, OrgId: obj.id == "#" ? OrgId : orgid, iscurrentDept: obj.original ? !obj.original.IsEdited : true, isloadjob: RecipientType == "2" ? 1 : 0 },
                        success: function (result) {
                            if (result != null && result.length > 0) {
                                callback.call(_self, result);
                            }
                            else {
                                callback.call(_self, []);
                            }
                        }
                    });

                }
            },
            "plugins": ["wholerow"]

        }).on('activate_node.jstree', function (obj, e) {
            if (!e.node.original.IsEdited) {
                return false;
            }
            $(myWorkflow.activtiyContainerForm).find("#RecipientId").val(e.node.original.DepartmentId);
            $(myWorkflow.activtiyContainerForm).find("#RecipientName").val(e.node.original.DepartmentName);
            myWorkflow.SaveActivity();
            $("#flow-Tree-JobFunction-modal").modal("hide");
        });
        $("#flow-Tree-JobFunction-modal").modal("show");
    },
    ///选择部门
    SelectDepartment: function ($this, OrgId, RecipientType) {
        if (OrgId == "") {
            return false;
        }
        $(".flow-Tree-Department").jstree('destroy').jstree({
            "core": {
                "check_callback": true,//默认为flase，会导致无法使用修改树结构。
                data: function (obj, callback) {
                    var _self = this;
                    var parentid = obj.id == "#" ? "" : obj.id;
                    var orgid = obj.id == "#" ? OrgId : obj.original.DepartmentId;
                    if (parentid != "" && !obj.original.IsEdited) {
                        orgid = obj.original.DepartmentId;
                    }
                    Ajax({
                        url: "/org/Organizations/GetOrgTree?t=" + new Date().toLocaleTimeString(),
                        data: { id: parentid, OrgId: obj.id == "#" ? OrgId : orgid, iscurrentDept: obj.original ? !obj.original.IsEdited : true, isloadjob: 0 },
                        success: function (result) {
                            if (result != null && result.length > 0) {
                                callback.call(_self, result);
                            }
                            else {
                                callback.call(_self, []);
                            }
                        }
                    });

                }
            },
            "plugins": ["wholerow"]

        }).on('activate_node.jstree', function (obj, e) {
            if (e.node.original.IsEdited) {
                return false;
            }
            $(myWorkflow.activtiyContainerForm).find("#RecipientId").val(e.node.original.DepartmentId);
            $(myWorkflow.activtiyContainerForm).find("#RecipientName").val(e.node.original.DepartmentName);
            myWorkflow.SaveActivity();
            $("#flow-Tree-Department-modal").modal("hide");
        });
        $("#flow-Tree-Department-modal").modal("show");
    },
    selectGroup: function ($this) {
        Notify.Remote({
            Title: "设置组",
            remote: "/ORG/Group/GroupTree?t=" + Math.random(),

            loaded: function (modal, id) {//初始化对象
                modal.find(".jstree").jstree({

                    "plugins": ["wholerow"]
                }).on('activate_node.jstree', function (obj, e) {

                    if (e.node.id != "#" && e.node.id != "0") {

                        $(myWorkflow.activtiyContainerForm).find("#RecipientId").val(e.node.id);
                        $(myWorkflow.activtiyContainerForm).find("#RecipientName").val(e.node.text);
                        myWorkflow.SaveActivity();
                        modal.modal("hide");
                    }

                });
            }
        });
    },
    selectParams: function ($this) {
        var flowparams = myWorkflow.FlowDesigner.flowParams;

        $(".flow-Tree-Params").jstree('destroy').jstree({
            'core': {
                "check_callback": true,
                'data': function (obj, callback) {
                    var newdata = [];
                    if (flowparams != null) {
                        $.each(flowparams, function (nguid, param) {
                            if (!param.IsDeleted) {
                                newdata.push(param);
                            }
                        });
                    }
                    //, 'selected': true 
                    callback.call(obj, [{
                        "text": myWorkflow.FlowDesigner.Flow.FlowName + "参数",
                        "icon": "fa fa-gears",
                        "id": "0",
                        'state': { 'opened': true },
                        "children": newdata
                    }]);
                }
            },

            "plugins": ["wholerow"]
        }).on('activate_node.jstree', function (obj, e) {

            if (e.node.id != "#" && e.node.id != "0") {

                $(myWorkflow.activtiyContainerForm).find("#RecipientId").val(e.node.id);
                $(myWorkflow.activtiyContainerForm).find("#RecipientName").val(e.node.text);
                myWorkflow.SaveActivity();
                $("#flow-Tree-Params-modal").modal("hide");
            }

        });
        $("#flow-Tree-Params-modal").modal("show");
    },
    selectSteps: function ($this, id) {
        var activities = myWorkflow.FlowDesigner.activities;
        $(".flow-Tree-step").jstree('destroy').jstree({
            'core': {
                "check_callback": true,
                'data': function (obj, callback) {
                    var newdata = [];
                    if (activities != null) {
                        $.each(activities, function (nguid, param) {
                            if (!param.IsDeleted && param.ActivityType != "5" && nguid != id) {
                                //param1.id = nguid;
                                //param1.text = param1.ActivityName.
                                //param1.icon = "fa fa-gear";
                                //param1.parent = "0";
                                newdata.push($.extend(true, param, { id: nguid, text: param.ActivityName, icon: "fa fa-gear", parent: "0" }));
                            }
                        });
                    }
                    //, 'selected': true 
                    callback.call(obj, [{
                        "text": myWorkflow.FlowDesigner.Flow.FlowName + "节点",
                        "icon": "fa fa-gears",
                        "id": "0",
                        'state': { 'opened': true },
                        "children": newdata
                    }]);
                }
            },

            "plugins": ["wholerow"]
        }).on('activate_node.jstree', function (obj, e) {

            if (e.node.id != "#" && e.node.id != "0") {

                $(myWorkflow.activtiyContainerForm).find("#RecipientId").val(e.node.id);
                $(myWorkflow.activtiyContainerForm).find("#RecipientName").val(e.node.text);
                myWorkflow.SaveActivity();
                $("#flow-Tree-step-modal").modal("hide");
            }

        });
        $("#flow-Tree-step-modal").modal("show");
    },
    selectProcess: function ($this, flowType) {

        $(".flow-flowProcess-step").jstree('destroy').jstree({
            'core': {
                "check_callback": true,//默认为flase，会导致无法使用修改树结构。
                data: function (obj, callback) {
                    var _self = this;

                    Ajax({
                        url: BaseUrl + "/flow/GetTree",
                        data: { parentid: flowType, IsType: 1 },
                        success: function (result) {
                            if (result != null && result.length > 0) {
                                var newdata = [];
                                for (var i = 0; i < result.length; i++) {
                                    result[i].children = false;
                                    result[i].icon = "fa fa-gear";
                                    //newdata.push(result[i]);
                                    if (result[i].FlowTypeId != myWorkflow.FlowDesigner.Flow.FlowId) {
                                        result[i].children = false;
                                        newdata.push(result[i]);
                                    }
                                }
                                callback.call(_self, {
                                    "text": "子流程",
                                    "icon": "fa fa-gears",
                                    "id": flowType,
                                    'state': { 'opened': true },
                                    "children": newdata
                                });
                            }
                            else {
                                callback.call(_self, {
                                    "text": "子流程",
                                    "icon": "fa fa-gears",
                                    "id": flowType,
                                    'state': { 'opened': true },
                                    "children": []
                                });
                            }
                        }
                    });

                }
            },

            "plugins": ["wholerow"]
        }).on('activate_node.jstree', function (obj, e) {

            if (e.node.id != "#" && e.node.id != "0") {

                $(myWorkflow.activtiyContainerForm).find("#RecipientId").val(e.node.id);
                $(myWorkflow.activtiyContainerForm).find("#RecipientName").val(e.node.text);
                myWorkflow.SaveActivity();
                $("#flow-flowProcess-modal").modal("hide");
            }

        });
        $("#flow-flowProcess-modal").modal("show");
    }

};

var QueryFilter = {
    RuleContainer: null,
    fields: [],
    editorCounter: 0,
    strings: {
        "and": "并且",
        "or": "或者",
        "equal": "相等",
        "notequal": "不相等",
        "startwith": "以..开始",
        "endwith": "以..结束",
        "like": "相似",
        "greater": "大于",
        "greaterorequal": "大于或等于",
        "less": "小于",
        "lessorequal": "小于或等于",
        "in": "包括在...",
        "notin": "不包括...",
        "addgroup": "增加分组",
        "addrule": "增加条件",
        "deletegroup": "删除分组"
    },
    operators: ["equal", "notequal", "greater", "greaterorequal", "less", "lessorequal"],
    //operators: {
    //     string: ["equal", "notequal", "startwith", "endwith", "like", "greater", "greaterorequal", "less", "lessorequal", "in", "notin"],
    //    number: ["equal", "notequal", "greater", "greaterorequal", "less", "lessorequal", "in", "notin"]
    //},
    editors: {
        string: {
            create: function (container, field) {
                var input = $("<input type='text' class='form-control' name='" + field.name + "_query' id='" + field.name + "_query' />");

                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);
                if (field.value) {
                    input.val(field.value);
                }
                return input;
            },
            setValue: function (input, value) {
                input.val(value);
            },
            getValue: function (input) {
                return input.val();
            },
            destroy: function (input) {
                input.liger('destroy');
            }
        },
        date: {
            create: function (container, field) {
                var input = $("<input type='text' class='form-control'  name='" + field.name + "_query' id='" + field.name + "_query' />");
                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);
                // input.ligerDateEditor(field.editor.options || {});
                return input;
            },
            setValue: function (input, value) {
                input.liger('option', 'value', value);
            },
            getValue: function (input, field) {
                return input.liger('option', 'value');
            },
            destroy: function (input) {
                input.liger('destroy');
            }
        },
        number: {
            create: function (container, field) {
                var input = $("<input type='text' class='form-control'  name='" + field.name + "_query' id='" + field.name + "_query'/>");
                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);
                //var options = {
                //    minValue: field.minValue,
                //    maxValue: field.maxValue
                //};
                // input.ligerSpinner($.extend(options, field.editor.options || {}));
                return input;
            },
            setValue: function (input, value) {
                input.val(value);
            },
            getValue: function (input, field) {
                var isInt = field.type == "int";
                if (isInt)
                    return parseInt(input.val(), 10);
                else
                    return parseFloat(input.val());
            },
            destroy: function (input) {
                input.liger('destroy');
            }
        },
        combobox: {
            create: function (container, field) {
                var input = $("<select class='select2'  name='" + field.name + "_query' id='" + field.name + "_query'></select>");

                var div = $('<div class="form-group"></div>').append(input);
                container.append(input);
                //var options = {
                //    data: field.data,
                //    slide: false,
                //    valueField: field.editor.valueField || field.editor.valueColumnName,
                //    textField: field.editor.textField || field.editor.displayColumnName
                //};
                //$.extend(options, field.editor.options || {});
                //input.ligerComboBox(options);
                return input;
            },
            setValue: function (input, value) {
                input.liger('option', 'value', value);
            },
            getValue: function (input) {
                return input.liger('option', 'value');
            },
            destroy: function (input) {
                input.liger('destroy');
            }
        }
    },
    Init: function (container, fields) {
        this.fields = fields;
        var g = this;
        this.RuleContainer = container;
        g.addGroup(container.children(":eq(0)"));
        container.append(this._bulidGroupTableHtml(false, false));
        container.children("table").addClass("l-filter-group-frist");
        // g.addRule(container.children(":eq(0)"));
        $(container).find(".addgroup,.deletegroup,.addrule,.deleterole").on("click", function (e) {
            var e = this;
            var cn = $(this).attr("class");

            if (cn.indexOf("addgroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addGroup(jtable);
            }
            else if (cn.indexOf("deletegroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.deleteGroup(jtable);
            }
            else if (cn.indexOf("addrule") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addRule(jtable);
            }
            else if (cn.indexOf("deleterole") >= 0) {
                var rulerow = $(this).parent().parent();
                g.deleteRule(rulerow);
            }
        });
    },
    addGroup: function (jgroup) {
        var g = this;
        jgroup = $(jgroup || g.group);
        var lastrow = $(">tbody:first > tr:last", jgroup);
        var groupHtmlArr = [];
        groupHtmlArr.push('<tr class="l-filter-rowgroup"><td class="l-filter-cellgroup" colSpan="4">');
        var altering = !jgroup.hasClass("l-filter-group-alt");
        groupHtmlArr.push(g._bulidGroupTableHtml(altering, true));
        groupHtmlArr.push('</td></tr>');
        var row = $(groupHtmlArr.join(''));
        lastrow.after(row);
        row.find(".addgroup,.deletegroup,.addrule,.deleterole").on("click", function (e) {
            var e = this;
            var cn = $(this).attr("class");

            if (cn.indexOf("addgroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addGroup(jtable);
            }
            else if (cn.indexOf("deletegroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.deleteGroup(jtable);
            }
            else if (cn.indexOf("addrule") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addRule(jtable);
            }
            else if (cn.indexOf("deleterole") >= 0) {
                var rulerow = $(this).parent().parent();
                g.deleteRule(rulerow);
            }
        });
        return row.find("table:first");
    },
    //删除分组 
    deleteGroup: function (group) {
        var g = this;
        $("td.l-filter-value", group).each(function () {
            var rulerow = $(this).parent();
            $("select.fieldsel", rulerow).unbind();
            g.removeEditor(rulerow);
        });
        $(group).parent().parent().remove();
    },
    //增加一个条件
    //parm [jgroup] 分组的jQuery对象
    addRule: function (jgroup) {
        var g = this;
        jgroup = jgroup || g.group;
        var lastrow = $(">tbody:first > tr:last", jgroup);
        var rulerow = $(g._bulidRuleRowHtml());
        lastrow.after(rulerow);
        if (g.fields.length) {
            //如果第一个字段启用了自定义输入框
            g.appendEditor(rulerow, g.fields[0]);
        }

        //事件：字段列表改变时
        $("select.fieldsel", rulerow).bind('change', function () {
            var jopsel = $(this).parent().next().find("select:first");
            var fieldName = $(this).val();
            if (!fieldName) return;
            var field = g.getField(fieldName);
            //字段类型处理
            var fieldType = field.type || "string";
            var oldFieldtype = rulerow.attr("fieldtype");
            if (fieldType != oldFieldtype) {
                jopsel.html(g._bulidOpSelectOptionsHtml(fieldType));
                rulerow.attr("fieldtype", fieldType);
            }
            //当前的编辑器
            var editorType = null;
            //上一次的编辑器
            var oldEditorType = rulerow.attr("editortype");
            //   if (g.enabledEditor(field)) editorType = field.editor.type;
            if (oldEditorType) {
                //如果存在旧的输入框 
                g.removeEditor(rulerow);
            }
            if (editorType) {
                //如果当前选择的字段定义了输入框
                g.appendEditor(rulerow, field);
            } else {
                rulerow.removeAttr("editortype").removeAttr("editorid");

                $("td.l-filter-value:first", rulerow).html("<div class='form-group'><input type='text' class='form-control valtxt'  name='" + field.name + "_query' id='" + field.name + "_query'/></div>");
            }
        });
        rulerow.find(".deleterole").on("click", function (e) {
            var e = this;
            var cn = e.className;
            if (cn.indexOf("deleterole") >= 0) {
                var rulerow = $(e).parent().parent();
                g.deleteRule(rulerow);
            }
        });
        return rulerow;
    },

    //删除一个条件
    deleteRule: function (rulerow) {
        $("select.fieldsel", rulerow).unbind();
        this.removeEditor(rulerow);
        $(rulerow).remove();
    },
    //生成分组的html
    _bulidGroupTableHtml: function (altering, allowDelete) {
        var g = this;
        var tableHtmlArr = [];
        tableHtmlArr.push('<table cellpadding="0" cellspacing="0" border="0" class="l-filter-group');
        if (altering)
            tableHtmlArr.push(' l-filter-group-alt');
        tableHtmlArr.push('"><tbody>');
        tableHtmlArr.push('<tr class="l-filter-rowlast"><td class="l-filter-rowlastcell" align="right" colSpan="4">');
        //and or

        tableHtmlArr.push('<div data-toggle="buttons-checkbox" class="btn-group">');
        if (!allowDelete) {
            tableHtmlArr.push('<button  class="btn btn-primary btn-sm addgroup">' + g.strings['addgroup'] + '</button>');
        }
        tableHtmlArr.push('<button  class="btn btn-primary btn-sm addrule">' + g.strings['addrule'] + '</button>');
        //tableHtmlArr.push('<ul class="dropdown-menu">');
        //tableHtmlArr.push('<li class="addgroup"><a href="javascript://" >' + g.strings['addgroup'] + '</a></li>');
        //tableHtmlArr.push('<li class="addrule"><a href="javascript://">' + g.strings['addrule'] + '</a></li>');

        if (allowDelete)
            tableHtmlArr.push('<button  class="btn btn-primary btn-sm deletegroup">' + g.strings['deletegroup'] + '</button>');


        ////add group
        //tableHtmlArr.push('<button type="button" class="btn btn-primary btn-rounded addgroup">' + g.strings['addgroup'] + '</button>');
        ////add rule
        //tableHtmlArr.push('<button type="button" class="addrule">' + g.strings['addrule'] + '</button>');
        //if (allowDelete)
        //    tableHtmlArr.push('<button type="button"  class="deletegroup">' + g.strings['deletegroup'] + '</button>');

        tableHtmlArr.push('</div>');
        tableHtmlArr.push('<div class="form-group"><select class="groupopsel">');
        tableHtmlArr.push('<option value="and">' + g.strings['and'] + '</option>');
        tableHtmlArr.push('<option value="or">' + g.strings['or'] + '</option>');
        tableHtmlArr.push('</select></div>');
        tableHtmlArr.push('</td></tr>');

        tableHtmlArr.push('</tbody></table>');
        return tableHtmlArr.join('');
    },

    //生成字段值规则的html
    _bulidRuleRowHtml: function (fields) {
        var g = this;
        fields = g.fields;
        var rowHtmlArr = [];
        var fieldType = fields[0].type || "string";
        rowHtmlArr.push('<tr fieldtype="' + fieldType + '"><td class="l-filter-column">');
        rowHtmlArr.push('<div class="form-group"><select class="fieldsel">');
        for (var i = 0, l = fields.length; i < l; i++) {
            var field = fields[i];
            rowHtmlArr.push('<option value="' + field.name + '"');
            if (i == 0) rowHtmlArr.push(" selected ");
            rowHtmlArr.push('>');
            rowHtmlArr.push(field.display);
            rowHtmlArr.push('</option>');
        }
        rowHtmlArr.push("</select></div>");
        rowHtmlArr.push('</td>');

        rowHtmlArr.push('<td class="l-filter-op">');
        rowHtmlArr.push('<div class="form-group"><select class="opsel">');
        rowHtmlArr.push(g._bulidOpSelectOptionsHtml(fieldType));
        rowHtmlArr.push('</select></div>');
        rowHtmlArr.push('</td>');
        rowHtmlArr.push('<td class="l-filter-value">');

        rowHtmlArr.push("<div class='form-group'><input type='text' class='form-control valtxt'  name='" + field.name + "_query' id='" + field.name + "_query'/></div>");
        rowHtmlArr.push('</td>');
        rowHtmlArr.push('<td>');
        rowHtmlArr.push('<div class="deleterole"><i class="fa fa-close" ></i></div>');
        rowHtmlArr.push('</td>');
        rowHtmlArr.push('</tr>');
        return rowHtmlArr.join('');
    },
    //删除编辑器
    removeEditor: function (rulerow) {
        var g = this;
        var type = $(rulerow).attr("editortype");
        var id = $(rulerow).attr("editorid");
        // var editor = g.editors[id];
        // if (editor) g.editors[type].destroy(editor);
        $("td.l-filter-value:first", rulerow).html("");
    },

    //获取一个运算符选择框的html
    _bulidOpSelectOptionsHtml: function (fieldType) {
        var ops = this.operators;

        var opHtmlArr = [];
        for (var i = 0, l = ops.length; i < l; i++) {
            var op = ops[i];
            opHtmlArr[opHtmlArr.length] = '<option value="' + op + '">';
            opHtmlArr[opHtmlArr.length] = this.strings[op];
            opHtmlArr[opHtmlArr.length] = '</option>';
        }
        return opHtmlArr.join('');
    },
    //附加一个输入框
    appendEditor: function (rulerow, field) {
        var g = this;

        var cell = $("td.l-filter-value:first", rulerow).html("");
        var editor = g.editors[field.type];
        g.editors[++g.editorCounter] = editor.create(cell, field);
        rulerow.attr("editortype", field.type).attr("editorid", g.editorCounter);

    },
    //获取分组数据
    getData: function (group) {
        var g = this;
        group = group || this.RuleContainer.children("table:eq(0)");

        var groupData = {};

        $("> tbody > tr", group).each(function (i, row) {
            var rowlast = $(row).hasClass("l-filter-rowlast");
            var rowgroup = $(row).hasClass("l-filter-rowgroup");
            if (rowgroup) {
                var groupTable = $("> td:last > table:last", row);
                if (groupTable.length) {
                    if (!groupData.groups) groupData.groups = [];
                    groupData.groups.push(g.getData(groupTable));
                }
            }
            else if (rowlast) {
                groupData.op = $(".groupopsel:first", row).val();
            }
            else {
                var fieldName = $("select.fieldsel:first", row).val();
                var field = g.getField(fieldName);
                var op = $(".opsel:first", row).val();
                var value = g._getRuleValue(row, field);
                var type = $(row).attr("fieldtype") || "string";
                if (!groupData.rules) groupData.rules = [];
                groupData.rules.push({
                    field: fieldName, op: op, value: value, type: type
                });
            }
        });

        return groupData;
    },
    //设置规则
    //parm [group] 分组数据
    //parm [jgruop] 分组table dom jQuery对象
    setData: function (group, jgroup) {
        var g = this;
        jgroup = jgroup || this.RuleContainer.children("table:eq(0)");
        var lastrow = $(">tbody:first > tr:last", jgroup);
        jgroup.find(">tbody:first > tr").not(lastrow).remove();
        $("select:first", lastrow).val(group.op);
        if (group.rules) {
            $(group.rules).each(function () {
                var rulerow = g.addRule(jgroup);
                rulerow.attr("fieldtype", this.type || "string");
                $("select.opsel", rulerow).val(this.op);
                $("select.fieldsel", rulerow).val(this.field).trigger('change');
                var editorid = rulerow.attr("editorid");
                if (editorid && g.editors[editorid]) {
                    var field = g.getField(this.field);
                    if (field && field.editor) {
                        g.editors[field.editor.type].setValue(g.editors[editorid], this.value, field);
                    }
                }
                else {
                    $(":text", rulerow).val(this.value);
                }
            });
        }
        if (group.groups) {
            $(group.groups).each(function () {
                var subjgroup = g.addGroup(jgroup);
                g.setData(this, subjgroup);
            });
        }
    },
    //根据fieldName 获取 字段
    getField: function (fieldname) {
        var g = this;
        for (var i = 0, l = g.fields.length; i < l; i++) {
            var field = g.fields[i];
            if (field.name == fieldname) return field;
        }
        return null;
    },
    _getRuleValue: function (rulerow, field) {
        var g = this;
        var editorid = $(rulerow).attr("editorid");
        var editortype = $(rulerow).attr("editortype");
        var editor = g.editors[editorid];

        if (editor)
            return g.editors[editortype].getValue(editor, field);

        return $(".valtxt:first", rulerow).val();
    }
};
$.fn.modal.Constructor.prototype.enforceFocus = function () { };